/**
 * Created by liuyubobobo on 14-4-11.
 * my site: http://www.liuyubobobo.com
 */

var board = new Array();
var score = 0;
var hasConflicted = new Array();
var type = 0;

window.onload = function(){
    prepareForMobile();
    newgame();
};


function setType(num){
    type = num;
}
//function getType(){
//    return type;
//}
function prepareForMobile(){
    if( documentWidth > 500 ){
        gridContainerWidth = 500;
        cellSpace = 20;
        cellSideLength = 100;
    }

    for(var i = 0; i < VERSIONS.length; i++){
        document.getElementById("gameButton").innerHTML += '<a href="javascript:newgame();" onclick="setType('+i+')">'+VERSIONS[i].name+'</a>'
    }


    document.getElementById("grid-container").innerHTML += '<div id="cell-container"></div>';

    var grid_cont = document.getElementById("grid-container");
    var cell_cont = document.getElementById("cell-container");
    var grid_cell = document.getElementsByClassName("grid-cell");

    grid_cont.style.width = gridContainerWidth - 2*cellSpace  + "px";
    grid_cont.style.height = gridContainerWidth - 2*cellSpace  + "px";
    grid_cont.style.padding = cellSpace  + "px";
    grid_cont.style.borderRadius = 0.02*gridContainerWidth;

    cell_cont.style.width = gridContainerWidth - 2*cellSpace + "px";
    cell_cont.style.height = gridContainerWidth - 2*cellSpace + "px";
    cell_cont.style.borderRadius = 0.02*gridContainerWidth;


    for (var k = 0, length = grid_cell.length; k < length; k++) {
        grid_cell[k].style.width = cellSideLength + "px";
        grid_cell[k].style.height = cellSideLength + "px";
        grid_cell[k].style.borderRadius = 0.02*cellSideLength;
    }
}

function newgame(){
    init();
    generateOneNumber();
    generateOneNumber();
}

function init(){
    for( var i = 0 ; i < 4 ; i++) {
        for (var j = 0; j < 4; j++) {
            var gridCell = document.getElementById('grid-cell-' + i + '-' + j);
            gridCell.style.top = getPosTop(i, j) + "px";
            gridCell.style.left = getPosLeft(i, j) + "px";
        }
    }
    for( var i = 0 ; i < 4 ; i ++ ){
        board[i] = new Array();
        hasConflicted[i] = new Array();
        for( var j = 0 ; j < 4 ; j ++ ){
            board[i][j] = 0;
            hasConflicted[i][j] = false;
        }
    }
    updateBoardView();
    score = 0;
}
function removeNumCell() {
    var content=document.getElementById("cell-container");
    var nodelist = content.childNodes;
    for(var i = nodelist.length-1;i>=0;i--) {
        content.removeChild(nodelist[i]);
    }
}
function updateBoardView(){
    removeNumCell();
    var number_cell=document.getElementsByClassName("number-cell");
    for( var i = 0 ; i < 4 ; i ++ ) {
        for (var j = 0; j < 4; j++) {
            var content=document.getElementById("cell-container");
            content.innerHTML += '<div class="number-cell" id="number-cell-' + i + '-' + j + '"></div>';
            var theNumberCell = document.getElementById('number-cell-' + i + '-' + j);

            if (board[i][j] == 0) {
                theNumberCell.style.width = '0px';
                theNumberCell.style.height = '0px';
                theNumberCell.style.top = getPosTop(i, j) + cellSideLength / 2  + "px";
                theNumberCell.style.left = getPosLeft(i, j) + cellSideLength / 2  + "px";
            } else {
                theNumberCell.style.width = cellSideLength  + "px";
                theNumberCell.style.height = cellSideLength  + "px";
                theNumberCell.style.top = getPosTop(i, j)  + "px";
                theNumberCell.style.left = getPosLeft(i, j)  + "px";
                theNumberCell.style.background = getNumberBackgroundColor(board[i][j]);
                theNumberCell.style.color = getNumberColor(board[i][j]);
                theNumberCell.innerText = VERSIONS[type].array[board[i][j]];
            }
            hasConflicted[i][j] = false;
        }
    }
    for (var i = 0; i < number_cell.length; i++){
        //number_cell[i].style.lineHeight = cellSideLength+'px';
        number_cell[i].style.fontSize = VERSIONS[type].size*cellSideLength+'px';
    }
}

function generateOneNumber(){

    if( nospace( board ) )
        return false;

	 var count=0;
	 var temporary=new Array();
	 for(var i=0;i<4;i++)
		 for(var j=0;j<4;j++) {
			 if(board[i][j]==0) {
				 temporary[count]=i*4+j;
				 count++;
			 }
		 }
	 var pos= parseInt( Math.floor( Math.random()  * count ) );

	 var randx=Math.floor(temporary[pos]/4);
	 var randy=Math.floor(temporary[pos]%4);

    var randNumber = Math.random() < 0.5 ? 1 : 2;

    board[randx][randy] = randNumber;
    showNumberWithAnimation( randx , randy , VERSIONS[type].array[randNumber],randNumber );

    return true;
}

document.onkeydown = function( event ){
	//event.preventDefault();
    switch( event.keyCode ){
        case 37: //left
            if( moveLeft() ){
                setTimeout("generateOneNumber()",210);
                setTimeout("isgameover()",300);
            }
            break;
        case 38: //up
            if( moveUp() ){
                setTimeout("generateOneNumber()",210);
                setTimeout("isgameover()",300);
            }
            break;
        case 39: //right
            if( moveRight() ){
                setTimeout("generateOneNumber()",210);
                setTimeout("isgameover()",300);
            }
            break;
        case 40: //down
            if( moveDown() ){
                setTimeout("generateOneNumber()",210);
                setTimeout("isgameover()",300);
            }
            break;
        default: //default
            break;
    }
};

function isgameover(){
    if( nospace( board ) && nomove( board ) ){
        gameover();
    }
}

function gameover(){
    alert('gameover!');
}

function moveLeft(){

    if( !canMoveLeft( board ) )
        return false;

    //moveLeft
    for( var i = 0 ; i < 4 ; i ++ )
        for( var j = 1 ; j < 4 ; j ++ ){
            if( board[i][j] != 0 ){

                for( var k = 0 ; k < j ; k ++ ){
                    if( board[i][k] == 0 && noBlockHorizontal( i , k , j , board ) ){
                        //move
                        showMoveAnimation( i , j , i , k );
                        board[i][k] = board[i][j];
                        board[i][j] = 0;
                        continue;
                    }
                    else if( board[i][k] == board[i][j] && noBlockHorizontal( i , k , j , board ) && !hasConflicted[i][k] ){
                        //move
                        showMoveAnimation( i , j , i , k );
                        //add
                        board[i][k] += 1;
                        board[i][j] = 0;
                        //add score
                        score += board[i][k];
                        updateScore( score );

                        hasConflicted[i][k] = true;
                        continue;
                    }
                }
            }
        }

    setTimeout("updateBoardView()",200);
    return true;
}

function moveRight(){
    if( !canMoveRight( board ) )
        return false;

    //moveRight
    for( var i = 0 ; i < 4 ; i ++ )
        for( var j = 2 ; j >= 0 ; j -- ){
            if( board[i][j] != 0 ){
                for( var k = 3 ; k > j ; k -- ){

                    if( board[i][k] == 0 && noBlockHorizontal( i , j , k , board ) ){
                        //move
                        showMoveAnimation( i , j , i , k );
                        board[i][k] = board[i][j];
                        board[i][j] = 0;
                        continue;
                    }
                    else if( board[i][k] == board[i][j] && noBlockHorizontal( i , j , k , board ) && !hasConflicted[i][k] ){
                        //move
                        showMoveAnimation( i , j , i , k);
                        //add
                        board[i][k] += 1;
                        board[i][j] = 0;
                        //add score
                        score += board[i][k];
                        updateScore( score );

                        hasConflicted[i][k] = true;
                        continue;
                    }
                }
            }
        }

    setTimeout("updateBoardView()",200);
    return true;
}

function moveUp(){

    if( !canMoveUp( board ) )
        return false;

    //moveUp
    for( var j = 0 ; j < 4 ; j ++ )
        for( var i = 1 ; i < 4 ; i ++ ){
            if( board[i][j] != 0 ){
                for( var k = 0 ; k < i ; k ++ ){

                    if( board[k][j] == 0 && noBlockVertical( j , k , i , board ) ){
                        //move
                        showMoveAnimation( i , j , k , j );
                        board[k][j] = board[i][j];
                        board[i][j] = 0;
                        continue;
                    }
                    else if( board[k][j] == board[i][j] && noBlockVertical( j , k , i , board ) && !hasConflicted[k][j] ){
                        //move
                        showMoveAnimation( i , j , k , j );
                        //add
                        board[k][j] += 1;
                        board[i][j] = 0;
                        //add score
                        score += board[k][j];
                        updateScore( score );

                        hasConflicted[k][j] = true;
                        continue;
                    }
                }
            }
        }

    setTimeout("updateBoardView()",200);
    return true;
}

function moveDown(){
    if( !canMoveDown( board ) )
        return false;

    //moveDown
    for( var j = 0 ; j < 4 ; j ++ )
        for( var i = 2 ; i >= 0 ; i -- ){
            if( board[i][j] != 0 ){
                for( var k = 3 ; k > i ; k -- ){

                    if( board[k][j] == 0 && noBlockVertical( j , i , k , board ) ){
                        //move
                        showMoveAnimation( i , j , k , j );
                        board[k][j] = board[i][j];
                        board[i][j] = 0;
                        continue;
                    }
                    else if( board[k][j] == board[i][j] && noBlockVertical( j , i , k , board ) && !hasConflicted[k][j] ){
                        //move
                        showMoveAnimation( i , j , k , j );
                        //add
                        board[k][j] += 1;
                        board[i][j] = 0;
                        //add score
                        score += board[k][j];
                        updateScore( score );

                        hasConflicted[k][j] = true;
                        continue;
                    }
                }
            }
        }

    setTimeout("updateBoardView()",200);
    return true;
}